package com.xca.rxjavademo.views;

import android.Manifest;
import android.app.AlertDialog;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.xca.rxjavademo.R;
import com.xca.rxjavademo.adapter.WeatherDayAdapter;
import com.xca.rxjavademo.adapter.WeatherWeekAdapter;
import com.xca.rxjavademo.base.BaseActivity;
import com.xca.rxjavademo.contract.WeatherContact;
import com.xca.rxjavademo.entity.Weather;
import com.xca.rxjavademo.presenter.WeatherPresenter;
import com.xca.rxjavademo.utils.EditTextUtils;
import com.xca.rxjavademo.utils.TimeUtils;
import com.xca.rxjavademo.utils.WeatherBackgroundUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class WeatherActivity extends BaseActivity implements WeatherContact.WeatherView , View.OnClickListener {
    private RelativeLayout relativeLayout ;
    private EditText wLocal ;
    private ImageView wSearch ;
    private boolean isGetFocus = false ;
    private WeatherContact.WeatherPresenter presenter ;
    private WeatherDayAdapter adapter1 ;
    private WeatherWeekAdapter adapter2 ;
    private List<Weather.Result.HourlyForecast> list1 ;
    private List<Weather.Result.ForecastList> list2 ;
    private TextView wAqi , wTomorrow , wTemperature , wWeather , wTime , wTips , wNight , wAir , wWind , wUpdateTime;
    private RecyclerView rv1 , rv2 ;
    private ImageView wAlert ;

    private LayoutInflater inflater ;


    private static final int REQUEST_LOCATION_PERMISSION = 1;
    private LocationManager locationManager;
    private LocationListener locationListener;

    @Override
    public int getLayoutId() {
        return R.layout.activity_weather;
    }

    @Override
    public void init() throws IOException {
        relativeLayout = findViewById(R.id.w1);
        wLocal = findViewById(R.id.w_local);
        wSearch = findViewById(R.id.w_search);
        wAqi = findViewById(R.id.w_aqi);
        wTomorrow = findViewById(R.id.w_tomorrow);
        wTemperature = findViewById(R.id.w_temp);
        wWeather = findViewById(R.id.w_weather);
        wTime = findViewById(R.id.w_time);
        wTips = findViewById(R.id.w_tips);
        wNight = findViewById(R.id.w_night_weather);
        wAir = findViewById(R.id.w_air);
        wWind = findViewById(R.id.w_wind);
        wAlert = findViewById(R.id.w_alert);
        rv1 = findViewById(R.id.w_dateList);
        rv2 = findViewById(R.id.w_dateDayList);
        wUpdateTime = findViewById(R.id.w_updateTime);

        EditTextUtils.clearFocus(wLocal);
        inflater = LayoutInflater.from(this);

        presenter = new WeatherPresenter(this , this);
        String city = wLocal.getText().toString().trim() ;
        Log.d("当前城市", city);
        presenter.getData(city);

        rv1.setLayoutManager(new LinearLayoutManager(this , LinearLayoutManager.HORIZONTAL, false));
        rv2.setLayoutManager(new LinearLayoutManager(this , LinearLayoutManager.VERTICAL, false));

        list1 = new ArrayList<>() ;
        list2 = new ArrayList<>();

        adapter1 = new WeatherDayAdapter(list1 , this , this);
        adapter2 = new WeatherWeekAdapter(list2 , this , this);

        rv1.setAdapter(adapter1);
        rv2.setAdapter(adapter2);

       wSearch.setOnClickListener(this);

    }

    @Override
    public void showData(Weather weather) {
        setWeatherBackground(weather.getResult().getCurrent_condition());
        showData1(weather);
        showData2(weather);
        showData3(weather);
        showData4(weather);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        String text = wLocal.getText().toString().trim();
        if (id == R.id.w_search){
            if (!isGetFocus){
                EditTextUtils.getFocus(wLocal);
                isGetFocus = true ;
            }else {
                if (wLocal == null || text.isEmpty()) {
                    Toast.makeText(this, "请输入城市名称", Toast.LENGTH_SHORT).show();
                }else {
                    EditTextUtils.clearFocus(wLocal);
                    isGetFocus = false ;
                    presenter.getData(text);
                }
            }
        }
    }

        private void showData1(@NonNull Weather weather){
        wAqi.setText(String.valueOf(weather.getResult().getAqi()));
        wTemperature.setText(String.valueOf(weather.getResult().getCurrent_temperature()));
        if (weather.getResult().getAlert()==null){
            wAlert.setVisibility(View.GONE);
        }else {
            wAlert.setVisibility(View.VISIBLE);
        }
        wWeather.setText(weather.getResult().getCurrent_condition() + " " +
                String.valueOf(weather.getResult().getDat_low_temperature()) + "~" +
                String.valueOf(weather.getResult().getDat_high_temperature()) + "℃");
            Log.d("最高温度", String.valueOf(weather.getResult().getDat_high_temperature()));
        wTime.setText(TimeUtils.getTime()[0]);
        wTips.setText("tips:" +weather.getResult().getTips());
        }

        private void showData2(@NonNull Weather weather){
        list1 = weather.getResult().getHourly_forecast();
        adapter1.updateData(list1);
        list2 = weather.getResult().getForecast_list();
        adapter2.updateData(list2);
        }

        private void showData3(@NonNull Weather weather){
        wNight.setText(weather.getResult().getNight_condition());
        wAir.setText(weather.getResult().getQuality_level());
        wWind.setText(weather.getResult().getWind_direction() + " " + String.valueOf(weather.getResult().getWind_level()) + "级" );
        wUpdateTime.setText(weather.getResult().getUpdate_time());
        }
        private void showData4(@NonNull Weather weather){
        wTomorrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDetailDialog(weather.getResult());
            }
        });
        wAlert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDetailDialog2(weather.getResult().getAlert().get(0));
            }
        });
        }

    private void setWeatherBackground(String weatherType) {
        String url = WeatherBackgroundUtils.getBackgroundUrl(weatherType);
        Glide.with(this)
                .asDrawable()
                .load(url)
                .centerCrop()//居中裁剪
                .into(new CustomTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        relativeLayout.setBackground(resource);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    private void showDetailDialog(Weather.Result result){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = inflater.inflate(R.layout.alert_weather, null);
        TextView waTitle , waContent , waLevel , waName , waType , waUpdateTime;
        waTitle = view.findViewById(R.id.wa_title);
        waContent = view.findViewById(R.id.wa_content);
        waLevel = view.findViewById(R.id.wa_level);
        waName = view.findViewById(R.id.wa_name);
        waType = view.findViewById(R.id.wa_type);
        waUpdateTime = view.findViewById(R.id.wa_update_time);
        waTitle.setText("明天天气");
        waContent.setText("明日天气：" + result.getTomorrow_condition());
        waLevel.setText("明日气温：" + String.valueOf(result.getTomorrow_low_temperature() + "~" + result.getTomorrow_high_temperature()) + "℃");
        waName.setText("明日空气质量：" + result.getTomorrow_quality_level());
        waType.setText("明日Aqi：" + String.valueOf(result.getTomorrow_aqi()));
        waUpdateTime.setVisibility(View.GONE);
        builder.setView(view)
                .create().show();
    }

    private void showDetailDialog2(Weather.Result.Alert alert){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = inflater.inflate(R.layout.alert_weather, null);
        TextView waTitle , waContent , waLevel , waName , waType , waUpdateTime;
        waTitle = view.findViewById(R.id.wa_title);
        waContent = view.findViewById(R.id.wa_content);
        waLevel = view.findViewById(R.id.wa_level);
        waName = view.findViewById(R.id.wa_name);
        waType = view.findViewById(R.id.wa_type);
        waUpdateTime = view.findViewById(R.id.wa_update_time);
        waTitle.setText(alert.getTitle());
        waContent.setText(alert.getContent());
        waLevel.setText(alert.getName());
        waName.setText(alert.getType());
        waType.setText(String.valueOf(alert.getLevel()));
        waUpdateTime.setText(alert.getUpdate_time());
        builder.setView(view)
                .create().show();
    }

}

